<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-col :xs="24" :sm="22">
          <el-input v-model="query.rolename" class="filter-item" style="width: 200px;" placeholder="名称" clearable />
          <el-input v-model="query.beizhu" class="filter-item" style="width: 200px;" placeholder="备注" clearable />
          <el-button class="filter-item" type="primary" @click="search()">查询</el-button>
          <el-button class="filter-item" @click="refresh()">刷新</el-button>
        </el-col>
        <el-col :xs="24" :sm="2" style="text-align:right;">
          <el-button class="filter-item" type="primary" @click="add()">添加</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table v-loading="loading" :data="datas" :height="height" style="width: 100%" border >
      <el-table-column prop="id" label="ID" min-width="100" sortable="custom" fixed="left" />
      <el-table-column prop="rolename" label="名称" min-width="120" show-overflow-tooltip />
      <el-table-column prop="beizhu" label="备注" min-width="130" show-overflow-tooltip />
      <el-table-column label="操作" min-width="225" align="right" fixed="right">
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="userShow(row)">管理员</el-button>
          <el-button size="mini" type="success" @click="edit(row)">修改</el-button>
          <el-button size="mini" type="danger" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="count > 0" :total="count" :page.sync="query.page" :limit.sync="query.limit" @pagination="list" />
    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog" top="1vh" :before-close="cancel">
      <el-form ref="ref" :rules="rules" :model="model" label-width="100px" class="dialog-body" :style="{height:height+30+'px'}">
        <el-form-item label="名称" prop="rolename">
          <el-input v-model="model.rolename" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="beizhu">
          <el-input v-model="model.beizhu" clearable />
        </el-form-item>
        <!-- <el-form-item label="排序" prop="role_sort">
          <el-input v-model="model.sort" type="number" />
        </el-form-item> -->
        <el-form-item label="权限">
          <el-tree
            ref="permissionRef"
            :data="permissionTree"
            :default-checked-keys="model.permission_ids"
            :props="{children: 'children',label: 'name'}"
            :expand-on-click-node="false"
            node-key="id"
            default-expand-all
            show-checkbox
            highlight-current
            @check="permissionCheck"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 管理员列表 -->
    <el-dialog :title="userDialogTitle" :visible.sync="userDialog" width="65%" top="1vh">
      <el-table ref="userRef" v-loading="userLoad" :data="userData" :height="height+30" style="width: 100%" border>
        <el-table-column prop="id" label="用户ID" min-width="105" sortable="custom" fixed="left" />
        <el-table-column prop="username" label="账号" min-width="120" sortable="custom" />
        <el-table-column prop="fullname" label="姓名" min-width="120" />
        <el-table-column prop="remark" label="备注" width="100" />
        <el-table-column label="操作" min-width="90" align="right" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{ row }">
            <el-button size="mini" type="danger" @click="userRemove(row)">解除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="userCount > 0" :total="userCount" :page.sync="userQuery.page" :limit.sync="userQuery.limit" @pagination="user" />
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import { list as permissionTree } from '@/api/permission'
import { list, info, add, edit, del, user, userRemove } from '@/api/role'

export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      height: 680,
      loading: false,
      datas: [],
      count: 0,
      query: {
        page: 1,
        limit: 13
      },
      dialog: false,
      dialogTitle: '',
      model: {
        id: '',
        permission_ids: [],
        rolename: '',
        beizhu: '',
        sort: 200
      },
      rules: {
        rolename: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      permissionTree: [],
      userDialog: false,
      userDialogTitle: '',
      userLoad: false,
      userData: [],
      userCount: 0,
      userQuery: {
        page: 1,
        limit: 13
      }
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.list
        this.count = res.data.count
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加
    add() {
      this.dialog = true
      this.dialogTitle = '角色添加'
      permissionTree().then(res => {
        this.permissionTree = res.data.list
      })
      this.reset()
    },
    // 修改
    edit(row) {
      this.dialog = true
      this.dialogTitle = '角色修改：' + row.id
      permissionTree().then(res => {
        this.permissionTree = res.data.list
      })
      info({
        id: row.id
      }).then(res => {
        this.reset(res.data)
      })
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除角色 <span style="color:red">' + row.rolename + ' </span>吗？',
        '删除角色：' + row.id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.reset()
          this.list()
          this.$message.success(res.msg)
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    // 取消
    cancel() {
      this.dialog = false
      this.reset()
    },
    // 提交
    submit() {
      this.$refs['ref'].validate(valid => {
        if (valid) {
          this.loading = true
          //this.model.permission_ids = 
          //console.log(this.$refs.permissionRef.getCheckedKeys().concat(this.$refs.permissionRef.getHalfCheckedKeys()))
          if (this.model.id) {
            edit(this.model).then(res => {
              this.list()
              this.reset()
              this.dialog = false
              this.$message.success(res.msg)
            }).catch(() => {
              this.loading = false
            })
          } else {
            add(this.model).then(res => {
              this.list()
              this.reset()
              this.dialog = false
              this.$message.success(res.msg)
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['ref'] !== undefined) {
        this.$refs['ref'].resetFields()
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 排序
    sort(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_type = ''
      if (sort.order === 'ascending') {
        this.query.sort_type = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_type = 'desc'
        this.list()
      }
    },
    // 是否禁用
    isDisable(row) {
      this.loading = true
      disable({
        admin_role_id: row.admin_role_id,
        is_disable: row.is_disable
      }).then(res => {
        this.list()
        this.$message.success(res.msg)
      }).catch(() => {
        this.loading = true
      })
    },
    // 菜单选择
    permissionCheck(data, node) {
      // this.$permissionRef.tree.getCheckedKeys().concat(this.$permissionRef.tree.getHalfCheckedKeys()) 
      this.model.permission_ids = node.checkedKeys
      //this.model.permission_ids = this.$refs.permissionRef.getCheckedKeys().concat(this.$refs.permissionRef.getHalfCheckedKeys())
    },
    // 管理员显示
    userShow(row) {
      this.userDialog = true
      this.userDialogTitle = '角色管理员：' + row.rolename
      this.userQuery.role_id = row.id
      this.user()
    },
    // 管理员列表
    user() {
      this.userLoad = true
      user(this.userQuery).then(res => {
        this.userData = res.data.list
        this.userCount = res.data.count
        this.userLoad = false
        this.$nextTick(() => {
          this.$refs['userRef'].doLayout()
        })
      }).catch(() => {
        this.userLoad = false
      })
    },
    // 管理员解除
    userRemove(row) {
      this.$confirm(
        '确定要解除该角色与管理员 <span style="color:red">' + row.username + ' </span>的关联吗？',
        '解除管理员：' + row.id,
        { type: 'warning', dangerouslyUseHTMLString: true }
      ).then(() => {
        this.userLoad = true
        userRemove({
          role_id: this.userQuery.role_id,
          user_id: row.id
        }).then(res => {
          this.user()
          this.$message.success(res.msg)
        }).catch(() => {
          this.userLoad = false
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
